package com.henu.acmrating.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * JWT 工具类
 */

@Component
public class JwtUtils {


    /**
     * 过期时间为一天
     * TODO 正式上线更换为15天
     */
    private static final long EXPIRE_TIME = 15 * 24 * 60 * 60 * 1000;

    /**
     * token私钥
     */
    private static String TOKEN_SECRET;

    @Value("${jwt.TOKEN_SECRET}")
    public void setUrl(String url) {
        JwtUtils.TOKEN_SECRET = url;
    }

    /**
     * 获取当前时间
     */
    public static Date getDate() {
        return new Date(System.currentTimeMillis());
    }

    /**
     * 生成签名,15分钟后过期
     *
     * @param userId 用户id
     * @return 返回签名
     */
    public static String sign(String userId) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //userID生成签名
        return JWT.create().withHeader(header).withAudience(userId)
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     * 验证签名，返回userId
     *
     * @param token 签名
     * @return 如果为0，说明token错误
     */
    public static Integer verity(String token) {
        int userId = 0;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
        } catch (Exception ignored) {
        }
        return userId;
    }

    public static Integer getUserId(HttpServletRequest request) {
        return verity(request.getHeader("token"));
    }
}
